/*
 * =====================================================================================
 *
 *       Filename:  FileSharing.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  10/12/2012 10:25:57 AM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (), 
 *   Organization:  
 *
 * =====================================================================================
 */
#include <string>
#include <ostream>
#include <istream>
#include <iostream>
#include <ios>
#include <fstream>
#include "../Headers/types.h"
#include "../Headers/authr.h"
#include "../Headers/log.h"
#include "FileSharing.h"

using namespace TOB;

/* FS_File */
FS_File::FS_File() {}

FS_File::~FS_File() {
	for ( std::map<std::string, std::ifstream *>::iterator i = FS_File::file.begin(); i != FS_File::file.end(); ++i) 
	{
		(*i).second->close();
	}
	FS_File::file.clear();
}

/* private methods */
/* *
 * Open file
 * @param fileName File name
 * @return Error code
 * */
uint16 FS_File::open(std::string fileName) {
	std::ifstream * in = new std::ifstream;
	FS_File::file[fileName] = in;
	FS_File::file[fileName]->open(fileName.c_str(), std::ios::in|std::ios::binary);
	if (!FS_File::file[fileName]) {
		Log::error("Couldn't open file " + fileName);
		return Code::FS_FunctionCallFailure;  
	}
	return Code::Okay;
}
/* *
 * Close file
 * @param fileName File name
 * @return Error code
 * */
uint16 FS_File::close(std::string fileName) {
	FS_File::file[fileName]->close();
	delete FS_File::file[fileName];
	FS_File::file[fileName] = NULL;
	FS_File::file.erase(fileName);
}
/* *
 * Get Bytes
 * @param fileName File name
 * @param count Numbers of bytes
 * @param buffer Reference on buffer
 * @return Error code
 * */
uint8 FS_File::getBytes(std::string fileName, int count, char * buffer) {

	FS_File::file[fileName]->read(buffer, count);
	buffer[FS_File::file[fileName]->gcount() + 1] = '\0';
	//if (!FS_File::file[fileName]) {
	//	return Code::FS_FunctionCallFailure;
	//}
	return Code::Okay;
}
/* *
 * Get file size
 * @param fileName File name
 * @return File size
 * */
int FS_File::get_file_size(std::string filename) {
	FILE *p_file = NULL;
	p_file = fopen(filename.c_str(), "rb");
	fseek(p_file, 0, SEEK_END);
	int size = ftell(p_file);
	fclose(p_file);
	return size;
}
/* *
* Get file descriptor
* @param fileName File name
* @return &istream
* */
ifstream& getHandle(std::string fileName) {
  return file[fileName];
}


int main(int argc, char ** argv) {	
	return 0;
}
